# 解一道 LeetCode 中国招聘面试题
LeetCode 在其 github 上几道面试题,将代码发送 review 后可能获得免一轮面试的机会,其中就有一道 TypeScript 题目,主要考察如何编写复杂的 TypeScript 类型.
这个面试题目很有水平,如果能在几分钟内就整理好思路,那么候选人的TS水平大概率是没问题的,是有写有一定复杂度的TS底层库的能力.
一路从第一节读到现在的小伙伴,如果认真把前面的内容搞清楚的话,这道题也并不难,我们现在就利用之前的知识整合在一起,解一下这个面试题.
# 题目
# 问题定义
假设有一个叫 EffectModule 的类
class EffectModule {}
@前端进阶之旅: 代码已经复制到剪贴板
这个对象上的方法只可能有两种类型签名:
interface Action<T> {
payload?: T
type: string
}
asyncMethod<T, U>(input: Promise<T>): Promise<Action<U>>
syncMethod<T, U>(action: Action<T>): Action<U>
@前端进阶之旅: 代码已经复制到剪贴板
这个对象上还可能有一些任意的非函数属性:
interface Action<T> {
payload?: T;
type: string;
}
class EffectModule {
count = 1;
message = "hello!";
delay(input: Promise<number>) {
return input.then(i => ({
payload: `hello ${i}!`,
type: 'delay'
});
}
setMessage(action: Action<Date>) {
return {
payload: action.payload!.getMilliseconds(),
type: "set-message"
};
}
}
@前端进阶之旅: 代码已经复制到剪贴板
现在有一个叫 connect 的函数,它接受 EffectModule 实例,将它变成另一个一个对象,这个对象上只有EffectModule 的同名方法,但是方法的类型签名被改变了:
asyncMethod<T, U>(input: Promise<T>): Promise<Action<U>> 变成了
asyncMethod<T, U>(input: T): Action<U>
syncMethod<T, U>(action: Action<T>): Action<U> 变成了
syncMethod<T, U>(action: T): Action<U>
@前端进阶之旅: 代码已经复制到剪贴板
例子:
EffectModule 定义如下:
interface Action<T> {
payload?: T;
type: string;
}
class EffectModule {
count = 1;
